<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>编辑商品</span>
          <el-button @click="goBack" type="primary" plain>返回列表</el-button>
        </div>
      </template>
      
      <el-form ref="goodsFormRef" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <!-- 商品分类选择 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="classId" required>
              <el-cascader
                v-model="selectedClassIds"
                :options="classOptions"
                :props="classProps"
                placeholder="请选择商品分类"
                clearable
                @change="handleClassChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺内分类" prop="businessClassId">
              <el-cascader
                v-model="selectedBusinessClassIds"
                :options="businessClassOptions"
                :props="businessClassProps"
                placeholder="请选择店铺内分类"
                clearable
                @change="handleBusinessClassChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName" required>
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品价格" prop="goodsPrice" required>
              <el-input-number 
                v-model="form.goodsPrice" 
                :precision="2" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="请输入商品价格"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品数量" prop="goodsNumber" required>
              <el-input-number 
                v-model="form.goodsNumber" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="请输入商品数量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入计量单位，如：个、件、kg等" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品状态" prop="goodsStatus" required>
              <el-switch
                v-model="form.goodsStatus"
                :active-value="1"
                :inactive-value="0"
                active-text="上架"
                inactive-text="下架"
                style="margin-left: 10px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品类型" prop="goodsVirtual">
              <el-radio-group v-model="form.goodsVirtual">
                <el-radio :label="0">实物商品</el-radio>
                <el-radio :label="1">虚拟商品</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 价格设置 -->
        <el-divider content-position="left">价格设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="积分价格" prop="goodsPoint">
              <el-input-number 
                v-model="form.goodsPoint" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="积分价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣价" prop="goodsDiscount">
              <el-input-number 
                v-model="form.goodsDiscount" 
                :precision="2" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="折扣价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="团购价" prop="goodsGroupPrice">
              <el-input-number 
                v-model="form.goodsGroupPrice" 
                :precision="2" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="团购价"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="秒杀价" prop="goodsMiaosha">
              <el-input-number 
                v-model="form.goodsMiaosha" 
                :precision="2" 
                :min="0" 
                :max="999999"
                style="width: 100%"
                placeholder="秒杀价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="积分商品" prop="goodsPointType">
              <el-switch
                v-model="form.goodsPointType"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣商品" prop="goodsDiscountType">
              <el-switch
                v-model="form.goodsDiscountType"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="秒杀商品" prop="goodsKillType">
              <el-switch
                v-model="form.goodsKillType"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="团购商品" prop="goodsGroupType">
              <el-switch
                v-model="form.goodsGroupType"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品图片和视频 -->
        <el-divider content-position="left">商品图片和视频</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品图片" prop="goodsImg">
              <ImageUpload v-model="form.goodsImg" :limit="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品视频" prop="goodsVideo">
              <FileUpload v-model="form.goodsVideo" :limit="1" :file-type="['mp4', 'avi', 'mov']" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 规格管理 -->
        <el-divider content-position="left">规格管理</el-divider>
        <div class="specs-container">
          <div v-if="specItems.length === 0" class="text-muted">该商品暂无规格</div>
          <div v-for="(specItem, specIndex) in specItems" :key="specIndex" class="spec-item">
            <el-card class="spec-card">
              <template #header>
                <div class="spec-header">
                  <span>{{ specItem.specName }}</span>
                  <el-tag type="warning" effect="plain">只读</el-tag>
                </div>
              </template>
              <div class="spec-values">
                <el-tag v-for="(value, idx) in specItem.values" :key="idx" type="info">{{ value }}</el-tag>
              </div>
            </el-card>
          </div>
        </div>

        <!-- SKU管理 -->
        <el-divider content-position="left">SKU管理</el-divider>
        <div class="sku-container">
          <el-alert title="SKU管理说明" type="info" :closable="false" show-icon style="margin-bottom: 15px;">
            <template #default>
              <p>• 商品价格将自动设置为所有SKU中的最低价格</p>
              <p>• 商品数量将自动计算为所有SKU库存的总和</p>
              <p>• 请为每个SKU填写价格、库存和货号信息</p>
            </template>
          </el-alert>
          <el-table :data="skuList" border style="width: 100%; margin-top: 20px;">
            <el-table-column label="#" type="index" width="50" />
            <el-table-column label="规格组合" min-width="200">
              <template #default="scope">
                <div class="sku-specs">
                  <el-tag v-for="(spec, index) in scope.row.specs" :key="index" type="info">{{ spec.name }}: {{ spec.value }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.price" placeholder="价格" type="number" min="0" step="0.01">
                  <template #append>元</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="库存" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.stock" placeholder="库存" type="number" min="0" />
              </template>
            </el-table-column>
            <el-table-column label="货号" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.skuCode" placeholder="货号" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-popconfirm title="确认删除该SKU？" @confirm="deleteSku(scope.row)">
                  <template #reference>
                    <el-button type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="GoodsEdit">
import * as goodsApi from "@/api/lkshop/goods";
import * as goodClassApi from "@/api/lkshop/good_class";
import * as businessClassApi from "@/api/lkshop/businessClass";
import * as goodsSpecsApi from "@/api/lkshop/goodspecs";
import * as specsApi from "@/api/lkshop/specs";
import * as skuApi from "@/api/lkshop/sku";
import * as relationApi from "@/api/lkshop/relation1";
import useUserStore from "@/store/modules/user";
import ImageUpload from "@/components/ImageUpload/index.vue";
import FileUpload from "@/components/FileUpload/index.vue";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();

const goodsFormRef = ref();
const loading = ref(true);
const submitLoading = ref(false);
const classOptions = ref([]);
const businessClassOptions = ref([]);
const selectedClassIds = ref([]);
const selectedBusinessClassIds = ref([]);

// 规格和SKU相关
const specItems = ref([]);
const skuList = ref([]);
// 初始加载的SKU主键集合，用于计算删除差集
const initialSkuIds = ref(new Set());

// 分类选择器配置
const classProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: false,
  expandTrigger: 'hover' // 鼠标悬停展开
};

const businessClassProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: false,
  expandTrigger: 'hover' // 鼠标悬停展开
};

const form = reactive({
  goodsId: null,
  businessId: null,
  goodsName: '',
  classId: null,
  goodsPrice: null,
  goodsPoint: null,
  goodsPointType: 0,
  goodsDiscountType: 0,
  goodsKillType: 0,
  goodsGroupType: 0,
  goodsGroupPrice: null,
  goodsDiscount: null,
  goodsMiaosha: null,
  goodsStatus: 1,
  goodsNumber: null,
  goodsImg: '',
  goodsVideo: '',
  businessClassId: null,
  goodsVirtual: 0,
  unit: ''
});

const rules = reactive({
  goodsName: [
    { required: true, message: "商品名称不能为空", trigger: "blur" }
  ],
  classId: [
    { required: true, message: "请选择商品分类", trigger: "change" }
  ],
  goodsPrice: [
    { required: true, message: "商品价格不能为空", trigger: "blur" }
  ],
  goodsNumber: [
    { required: true, message: "商品数量不能为空", trigger: "blur" }
  ],
  goodsStatus: [
    { required: true, message: "请选择商品状态", trigger: "change" }
  ]
});

/** 获取商品详情 */
function getGoodDetail() {
  const goodsId = route.params.goodsId;
  if (!goodsId) {
    proxy.$modal.msgError("商品ID不能为空");
    goBack();
    return;
  }
  
  loading.value = true;
  
  // 先确保分类数据已经加载完成
  Promise.all([
    new Promise(resolve => {
      if (classOptions.value.length > 0) {
        resolve();
      } else {
        // 如果分类数据还没加载，等待一下
        const checkInterval = setInterval(() => {
          if (classOptions.value.length > 0) {
            clearInterval(checkInterval);
            resolve();
          }
        }, 100);
        // 最多等待5秒
        setTimeout(() => {
          clearInterval(checkInterval);
          resolve();
        }, 5000);
      }
    }),
    new Promise(resolve => {
      if (businessClassOptions.value.length > 0) {
        resolve();
      } else {
        // 如果店铺分类数据还没加载，等待一下
        const checkInterval = setInterval(() => {
          if (businessClassOptions.value.length > 0) {
            clearInterval(checkInterval);
            resolve();
          }
        }, 100);
        // 最多等待5秒
        setTimeout(() => {
          clearInterval(checkInterval);
          resolve();
        }, 5000);
      }
    })
  ]).then(() => {
    // 分类数据准备好后，再获取商品详情
    goodsApi.getGood(goodsId).then(response => {
      Object.assign(form, response.data);
      setSelectedClassIds();
      setSelectedBusinessClassIds();
      // 加载已有SKU并回填
      return loadSkuAndSpecs(goodsId);
    }).then(() => {
      loading.value = false;
    }).catch(() => {
      loading.value = false;
      goBack();
    });
  }).catch(() => {
    loading.value = false;
    goBack();
  });
}

/** 根据已存在的SKU回推构建规格项 */
function buildSpecItemsFromSkuList() {
  const nameToValues = new Map();
  skuList.value.forEach(sku => {
    (sku.specs || []).forEach(p => {
      const name = (p.name || '').trim();
      const val = (p.value || '').trim();
      if (!name || !val) return;
      if (!nameToValues.has(name)) nameToValues.set(name, new Set());
      nameToValues.get(name).add(val);
    });
  });
  specItems.value = Array.from(nameToValues.entries()).map(([specName, set]) => ({
    specName,
    values: Array.from(set)
  }));
}

/** 加载SKU并构造编辑所需数据 */
function loadSkuAndSpecs(goodsId) {
  return skuApi.listSku({ goodsId }).then(res => {
    const rows = res.rows || res.data || [];
    skuList.value = rows.map(r => ({
      skuId: r.skuId,
      specs: safeParseJson(r.spec) || [],
      price: r.price,
      stock: r.goodsNumber,
      skuCode: r.skuCode
    }));
    initialSkuIds.value = new Set(rows.filter(r => r.skuId != null).map(r => r.skuId));
    buildSpecItemsFromSkuList();
  });
}

function safeParseJson(s) {
  try { return JSON.parse(s || '[]'); } catch { return []; }
}

/** 新增规格项 */
function addNewSpec() {
  specItems.value.push({ specName: '', values: [''] });
}

/** 删除规格项 */
function removeSpec(index) {
  specItems.value.splice(index, 1);
  generateSkuList();
}

/** 添加规格值 */
function addSpecValue(specIndex) {
  specItems.value[specIndex].values.push('');
}

/** 删除规格值 */
function removeSpecValue(specIndex, valueIndex) {
  specItems.value[specIndex].values.splice(valueIndex, 1);
  generateSkuList();
}

/** 生成SKU列表（保留已有行的价格/库存/货号） */
function generateSkuList() {
  const validSpecItems = specItems.value.filter(item => item.specName && item.values.some(v => (v || '').trim()));
  if (validSpecItems.length === 0) { skuList.value = []; return; }
  const combinations = generateCombinations(validSpecItems);
  const oldMap = new Map();
  skuList.value.forEach(row => oldMap.set(buildSpecKey(row.specs || []), row));
  skuList.value = combinations.map(combo => {
    const key = buildSpecKey(combo);
    const old = oldMap.get(key);
    return old ? { ...old, specs: combo } : { specs: combo, price: '', stock: '', skuCode: '' };
  });
}

/** 规格组合生成 */
function generateCombinations(items) {
  const res = [];
  function dfs(i, cur) {
    if (i === items.length) { res.push([...cur]); return; }
    const it = items[i];
    const vals = it.values.filter(v => (v || '').trim()).map(v => v.trim());
    for (const v of vals) { cur.push({ name: it.specName, value: v }); dfs(i + 1, cur); cur.pop(); }
  }
  dfs(0, []);
  return res;
}

function buildSpecKey(pairs) {
  return (pairs || [])
    .filter(p => (p.name || '').trim() && (p.value || '').trim())
    .sort((a,b) => a.name.localeCompare(b.name, 'zh'))
    .map(p => `${p.name.trim()}=${p.value.trim()}`)
    .join(';');
}

/** 保存规格与SKU（幂等） */
async function saveSpecsAndSku(goodsId) {
  const businessId = userStore.businessId;
  // 规格只读：仅确保关联存在（不允许在编辑页改动规格项和值）
  for (const item of specItems.value) {
    if (!item.specName) continue;
    const specResp = await goodsSpecsApi.addGoodspecs({ goodsSpecName: item.specName, businessId });
    const specId = specResp.data;
    await relationApi.addRelation1({ goodsId: Number(goodsId), goodsSpecId: Number(specId), businessId: Number(businessId) });
  }
  // 先删除用户在前端移除的SKU（仅当前商品）
  const currentIds = new Set(skuList.value.filter(r => r.skuId != null).map(r => r.skuId));
  const toDelete = Array.from(initialSkuIds.value).filter(id => !currentIds.has(id));
  for (const id of toDelete) {
    try { await skuApi.delSku(id); } catch (e) { /* 忽略单条删除失败，继续 */ }
  }
  // SKU
  for (const sku of skuList.value) {
    await skuApi.addSku({
      goodsId,
      businessId,
      spec: JSON.stringify(sku.specs || []),
      goodsNumber: parseInt(sku.stock),
      price: parseFloat(sku.price),
      skuCode: sku.skuCode
    });
  }
  // 保存后刷新初始集合
  initialSkuIds.value = new Set(skuList.value.filter(r => r.skuId != null).map(r => r.skuId));
}

/** 删除单条SKU（仅当前商品） */
function deleteSku(row) {
  skuList.value = skuList.value.filter(r => r !== row);
}

/** 设置商品分类选择器值 */
function setSelectedClassIds() {
  if (form.classId && classOptions.value.length > 0) {
    // 根据classId查找完整的分类路径
    const targetId = parseInt(form.classId);
    const path = findClassPath(classOptions.value, targetId);
    if (path.length > 0) {
      selectedClassIds.value = path;
      console.log("找到商品分类路径:", path);
    } else {
      // 如果找不到路径，设置为当前分类ID
      selectedClassIds.value = [targetId];
      console.log("没有找到商品分类路径，使用原始ID:", targetId);
    }
  }
}

/** 设置店铺分类选择器值 */
function setSelectedBusinessClassIds() {
  if (form.businessClassId && businessClassOptions.value.length > 0) {
    // 根据businessClassId查找完整的分类路径
    console.log(form.businessClassId+"店铺内分类的id");
    // 确保businessClassId是数字类型进行比较
    const targetId = parseInt(form.businessClassId);
    const path = findClassPath(businessClassOptions.value, targetId);
    if (path.length > 0) {
      selectedBusinessClassIds.value = path;
      console.log("找到店铺内分类", path);
    } else {
      // 如果找不到路径，设置为当前分类ID
      selectedBusinessClassIds.value = [targetId];
      console.log("没有找到店铺内分类，使用原始ID:", targetId);
    }
  }
}

/** 在树形数据中查找分类路径 */
function findClassPath(treeData, targetId) {
  const path = [];
  
  function findPath(nodes, target, currentPath = []) {
    for (const node of nodes) {
      const newPath = [...currentPath, node.id];
      
      // 确保类型一致进行比较
      if (parseInt(node.id) === parseInt(target)) {
        path.push(...newPath);
        return true;
      }
      
      if (node.children && node.children.length > 0) {
        if (findPath(node.children, target, newPath)) {
          return true;
        }
      }
    }
    return false;
  }
  
  findPath(treeData, targetId);
  return path;
}

/** 获取商品分类列表 */
function getClassList() {
  goodClassApi.getGood_classTree({}).then(response => {
    console.log('商品分类树形数据:', response.data);
    classOptions.value = response.data || [];
  }).catch((error) => {
    console.error('获取商品分类失败:', error);
    proxy.$modal.msgError("商品分类加载失败");
  });
}



/** 获取店铺分类列表 */
function getBusinessClassList() {
  // 使用用户存储中的商家ID
  const businessId = userStore.businessId;
  console.log('=== 商品编辑页面获取商家ID ===');
  console.log('用户存储:', userStore);
  console.log('用户存储中的商家ID:', businessId);
  console.log('用户存储中的用户ID:', userStore.id);
  
  if (!businessId) {
    console.warn('未找到商家ID，无法获取店铺分类');
    proxy.$modal.msgWarning("未找到商家信息，请重新登录");
    return;
  }
  
  console.log('开始获取店铺分类，商家ID:', businessId);
  businessClassApi.getBusinessClassTree({ businessId: businessId }).then(response => {
    console.log('店铺分类获取成功:', response);
    console.log('店铺分类树形数据:', response.data);
    businessClassOptions.value = response.data || [];
    console.log('店铺分类选项数量:', businessClassOptions.value.length);
    // 打印所有店铺分类的ID，用于调试
    const allIds = [];
    function collectIds(nodes) {
      nodes.forEach(node => {
        allIds.push(node.id);
        if (node.children && node.children.length > 0) {
          collectIds(node.children);
        }
      });
    }
    collectIds(businessClassOptions.value);
    console.log('所有店铺分类ID:', allIds);

  }).catch((error) => {
    console.error('获取店铺分类失败:', error);
    proxy.$modal.msgError("店铺分类加载失败");
  });
}

/** 构建树形数据 */
function buildTreeData(data) {
  if (!data || data.length === 0) {
    return [];
  }

  const map = {};
  const result = [];

  // 创建映射
  data.forEach(item => {
    if (item.id) {
      map[item.id] = { 
        id: item.id,
        name: item.name || item.className || '未命名分类',
        parentId: item.parentId,
        level: item.level,
        children: [] 
      };
    }
  });

  // 构建树形结构
  data.forEach(item => {
    if (item.id && map[item.id]) {
      const node = map[item.id];
      if (item.parentId && map[item.parentId]) {
        map[item.parentId].children.push(node);
      } else {
        result.push(node);
      }
    }
  });

  console.log('最终树形结果:', result);
  return result;
}

/** 商品分类选择变化 */
function handleClassChange(value) {
  if (value && value.length > 0) {
    form.classId = value[value.length - 1];
  } else {
    form.classId = null;
  }
}

/** 店铺分类选择变化 */
function handleBusinessClassChange(value) {
  if (value && value.length > 0) {
    form.businessClassId = value[value.length - 1];
  } else {
    form.businessClassId = null;
  }
}

/** 提交表单 */
function submitForm() {
  proxy.$refs.goodsFormRef.validate(valid => {
    if (valid) {
      submitLoading.value = true;
      if (skuList.value.length > 0) {
        const invalid = skuList.value.find(s => !s.price || !s.stock);
        if (invalid) { proxy.$modal.msgWarning("请填写完整的SKU信息（价格和库存）"); submitLoading.value = false; return; }
        const totalStock = skuList.value.reduce((sum, s) => sum + (parseInt(s.stock) || 0), 0);
        const prices = skuList.value.map(s => parseFloat(s.price) || 0).filter(p => p > 0);
        form.goodsNumber = totalStock;
        form.goodsPrice = prices.length > 0 ? Math.min(...prices) : 0;
      }

      goodsApi.updateGood(form).then(() => {
        return saveSpecsAndSku(form.goodsId);
      }).then(() => {
        proxy.$modal.msgSuccess("保存成功");
        goBack();
      }).catch(() => {
        submitLoading.value = false;
      });
    }
  });
}

/** 重置表单 */
function resetForm() {
  getGoodDetail();
}

/** 返回列表 */
function goBack() {
  router.push('/good2/goods');
}

// 初始化
getClassList();
getBusinessClassList();
getGoodDetail();
</script>
/* 规格和SKU样式 */
.specs-container { margin-bottom: 20px; }
.spec-item { margin-bottom: 20px; }
.spec-card { border: 1px solid #e4e7ed; }
.spec-header { display: flex; justify-content: space-between; align-items: center; }
.spec-values { display: flex; flex-direction: column; gap: 10px; }
.spec-value-item { display: flex; align-items: center; gap: 10px; }
.sku-container { margin-bottom: 20px; }
.sku-specs { display: flex; flex-wrap: wrap; gap: 5px; }

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-divider {
  margin: 20px 0;
}

/* 美化卡片 */
:deep(.el-card) {
  border-radius: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__header) {
  background: #409eff;
  color: #ffffff;
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-card__body) {
  padding: 24px;
}

/* 美化表单 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #333333;
  font-size: 16px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
}

/* 美化级联选择器 */
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader .el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

:deep(.el-cascader .el-input__wrapper.is-focus) {
  border-color: #409eff;
}

/* 美化数字输入框 */
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

/* 美化单选按钮组 */
:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-radio) {
  margin-right: 0;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background: #409eff;
  border-color: #409eff;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #409eff;
  font-weight: 600;
}

/* 美化按钮 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
}

:deep(.el-button--primary) {
  background: #409eff;
  border: 1px solid #409eff;
  color: #ffffff;
}

/* 美化分割线 */
:deep(.el-divider__text) {
  background: #ffffff;
  color: #409eff;
  font-weight: 600;
  font-size: 16px;
}

/* 美化文本域 */
:deep(.el-textarea__inner) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

/* 美化上传组件 */
:deep(.el-upload) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-upload-dragger) {
  border-radius: 6px;
  border: 2px dashed #e9ecef;
  background: #ffffff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-card__body) {
    padding: 20px;
  }
  
  :deep(.el-radio-group) {
    flex-direction: column;
    gap: 10px;
  }
}
</style> 